package cn.tedu.shoppingmall.controller;

import cn.tedu.shoppingmall.mapper.AddressMapper;
import cn.tedu.shoppingmall.mapper.TransactionMapper;
import cn.tedu.shoppingmall.mapper.UserMapper;
import cn.tedu.shoppingmall.vo.Address;
import cn.tedu.shoppingmall.vo.User;
import cn.tedu.shoppingmall.vo.UserDetail;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.constraints.NotNull;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Api(tags = "1用户模块")
@RestController
@RequestMapping("/mall")
public class MallUserController {
    @Autowired
    UserMapper userMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    TransactionMapper transactionMapper;
//头像
    @Value("${userdirPath}")
    private String dirPath;

    @PostMapping("/login")
    public String malllogin(@AuthenticationPrincipal UserDetails userDetails, User user, String rem, HttpServletResponse response){ //rem用来确认记住密码
        User u = userMapper.selectByUsername(userDetails.getUsername());
        if (u!=null){
            return "你已经登陆过了,请先注销登陆后,再登录"; //别轻易改,再前端login页面有判断
        }
        if (u!=null) {
            if (u.getPassword().equals(user.getPassword())) {
                if (rem!=null){
                    //存cookie里
                    Cookie c1 = new Cookie("un",u.getUsername());
                    Cookie c2 = new Cookie("pw",u.getPassword());
                    //设置时间
                    c1.setMaxAge(60*60*24*30);
                    c2.setMaxAge(60*60*24*30);
                    //通过响应对象 将Cookie下发给客户端
                    response.addCookie(c1);
                    response.addCookie(c2);
//                    System.out.println();

                }
                return "ok"; //登录成功
            }
            return "密码错误";  //密码错误
        }
        return "用户名不存在";  //用户名不存在
    }
    //设置用户信息缓存
    private Map<String,UserDetail> userDetailMap = new HashMap<>();

//    @PostMapping("/logOut")
//    public void logout(HttpSession session){
//        System.out.println("退出登录");
//        session.removeAttribute("u");
//    }
    @GetMapping("/getUser")
    public UserDetail GetMallUser(@AuthenticationPrincipal UserDetails user){
        if (user!=null){
//            //先判断集合里有没有用户信息,在判断UserDetails的值
//            if (    userDetailMap.get(user.getUsername())!=null
//                    &&
//                    userDetailMap.get(user.getUsername()).getUsername().equals(user.getUsername())
//            ){
//                //如果有信息,则直接走缓存,减轻数据库压力
//                System.out.println("缓存1=="+ userDetailMap.get(user.getUsername()));
//                return userDetailMap.get(user.getUsername());
//            }else {
////                System.out.println("无缓存:"+user.getUsername());
            User userold = userMapper.selectByUsername(user.getUsername());
                UserDetail userd = userMapper.findUserDetailByUserUsername(user.getUsername());
                List<Address> address = addressMapper.findAddressByUserUsername(user.getUsername());
                //将细节表的userid赋值，不然前台导航条不能正确显示！
                if(userd.getUserid()==null)
                    userd.setUserid(userold.getId());
                if (address.size()!=0)
                    userd.setAddresses(address);



//                //如果没有信息,则查询赋给缓存
//                userDetailMap.put(userd.getUsername(),userd);
//                System.out.println("新user进入:"+userd);
//                System.out.println("缓存2=="+ userDetailMap.get(user.getUsername()));
//                return userDetailMap.get(user.getUsername());
            return userd;
//            }
        }
        UserDetail userd = new UserDetail();
//        System.out.println("老=="+userd);
        userd.setId(0);
        return userd;
    }

    @GetMapping("/getUsers")
    public List<UserDetail> GetUsers(){
        List<UserDetail> users = userMapper.selectUserDetailAll();
        return users;
    }



    @PostMapping("/register")
    @Transactional
    public String register(@Validated User user, BindingResult result){
        if (result.hasErrors()){
            return result.getFieldError().getDefaultMessage();
        }
        if (userMapper.selectByUsername(user.getUsername())!=null){
            return "该用户名已存在!";
        }else {
            if (userMapper.selectByPhone(user.getPhone())!=null) {
                return "手机号已存在";
            }
            // 5.用户输入的密码进行加密操作
            PasswordEncoder encoder=new BCryptPasswordEncoder();
            String pwd=encoder.encode(user.getPassword().trim());
            user.setPassword(pwd);
            userMapper.insert(user);
            user = userMapper.selectByUsername(user.getUsername());
            UserDetail userDetail = new UserDetail()
                    .setUsername(user.getUsername())
                    .setUserid(user.getId())
                    .setAge(user.getAge())
                    .setNick(user.getNick())
                    .setPhone(user.getPhone());
            userMapper.insertUserDetail(userDetail);
            return "ok";
        }
    }

    public String addUserDetail(UserDetail userDetail){
        userMapper.insertUserDetail(userDetail);
        return "ok";
    }

    @PostMapping("/updateUserDetail")
    @Transactional
    public String updateUserDetail(UserDetail userDetail,BindingResult result, String address, String remark, MultipartFile picFile){
        if (result.hasErrors()){
            String msg = result.getFieldError().getDefaultMessage();
            return msg;
        }
        UserDetail user = userMapper.selectByUserid(userDetail.getUserid());

//        System.out.println("user = " + user);
        if ((user.getUsername()!=null && "".equals(user.getUsername())) && !"".equals(userDetail.getUsername())){
            return "用户名已存在";
        }else {
            if (userMapper.selectByPhone(userDetail.getPhone())!=null ) {
                return "手机号已存在";
            }
            if (user.getPhone().equals(userDetail.getPhone())){
                return "手机号是一样的啊";
            }
            //如果没写username就用原来的,以下同理
            if("".equals(userDetail.getUsername())) userDetail.setUsername(user.getUsername());
//            System.out.println("userDetail = " + userDetail);
            if("".equals(userDetail.getPhone()) && user.getPhone()!=null) userDetail.setPhone(user.getPhone());
            if("".equals(userDetail.getAge())) userDetail.setAge(user.getAge());
            if("".equals(userDetail.getNick())) userDetail.setNick(user.getNick());
            if("".equals(userDetail.getGender()) || userDetail.getGender()==null) userDetail.setGender(user.getGender());
            if("".equals(userDetail.getIntro())) userDetail.setIntro(user.getIntro());

//            System.out.println("更改后userDetail: "+userDetail+"==="+address+"++"+remark);

            //修改头像
            if (!picFile.isEmpty()){
                String fileName = picFile.getOriginalFilename();
                String suffix = fileName.substring(fileName.lastIndexOf("."));
                fileName = UUID.randomUUID()+suffix;
                //文件夹路径
                SimpleDateFormat f = new SimpleDateFormat("/yyyy/MM/dd/");
                //new Date()当前系统时间  /2021/12/20/
                String datePath = f.format(new Date());
                File dirFile = new File(dirPath+datePath);
                if (!dirFile.exists()){
                    dirFile.mkdirs();
                }
                //文件完整路径
                String filePath = dirPath+datePath+fileName;
                try {
                    //保存文件
                    picFile.transferTo(new File(filePath));
                } catch (IOException e) {
                    System.out.println("URL装配失败，请检查路径");
                }
                //如果修改用户资料路径,则需要把这个"user"也改了
                userDetail.setUrl("/user"+datePath+fileName);
            }else {
                //查询老信息
                UserDetail userDetailOld = userMapper.findUserDetailByUserUsername(user.getUsername());
                userDetail.setUrl(userDetailOld.getUrl());
            }
            //查询用户所购买过的所有订单金额及商品数量,分别赋值---调用下边方法
            UserDetail userDetailpriceAndSum = UpdateUserPriceAndSum(user.getUsername());
            userDetail.setPrice(userDetailpriceAndSum.getPrice()).setSum(userDetailpriceAndSum.getSum());

            //更新缓存
//            userDetailMap.put(userDetail.getUsername(),userDetailMap.remove(user.getUsername()));
            //更新user表
            userMapper.updateUsernameById(userDetail);
            //更新address表
            addressMapper.updateUsernameByUserId(userDetail);
            //更新订单表Transaction
            transactionMapper.updateUsernameByUserid(userDetail.getUsername(),userDetail.getUserid());

            userMapper.updateUserDetail(userDetail);
            if (!"".equals(address) || !"".equals(remark)){
                Address addresses = new Address();
                addresses.setAddressname(address).setRemark(remark).setUsername(user.getUsername()).setUserid(userDetail.getUserid());
                addressMapper.insertAddress(addresses);
            }

            return "ok";
        }

    }

    public UserDetail UpdateUserPriceAndSum(String username){
        UserDetail userDetail = userMapper.findUserDetailByUserUsername(username);
        userDetail.setSum(transactionMapper.getTransComsumByUsername(username));
        userDetail.setPrice(transactionMapper.getTransPriceByUsername(username));
        userMapper.UpdateUserPriceAndSum(userDetail);
        return userDetail;
    }
}
